package org.apache.solr.search.grouping.collector;

import java.io.IOException;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.Scorer;
import org.apache.solr.search.DocSet;

/**
 * A collector that filters incoming doc ids that are not in the filter.
 *
 * @lucene.experimental
 */
public class FilterCollector extends Collector {

    private final DocSet filter;
    private final Collector delegate;
    private int docBase;
    private int matches;

    public FilterCollector(DocSet filter, Collector delegate) {
        this.filter = filter;
        this.delegate = delegate;
    }

    @Override
    public void setScorer(Scorer scorer) throws IOException {
        delegate.setScorer(scorer);
    }

    @Override
    public void collect(int doc) throws IOException {
        matches++;
        if (filter.exists(doc + docBase)) {
            delegate.collect(doc);
        }
    }

    @Override
    public void setNextReader(AtomicReaderContext context) throws IOException {
        this.docBase = context.docBase;
        delegate.setNextReader(context);
    }

    @Override
    public boolean acceptsDocsOutOfOrder() {
        return delegate.acceptsDocsOutOfOrder();
    }

    public int getMatches() {
        return matches;
    }

    /**
     * Returns the delegate collector
     *
     * @return the delegate collector
     */
    public Collector getDelegate() {
        return delegate;
    }
}
